package com.wedjg.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author wedjg
 * @version 1.0
 * @date 2019/6/4
 */
@Slf4j
public class SemaphoreExnaple1 {

    private static final int THREAD_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 相当于设置n个令牌，只有拿到令牌的才能继续执行
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadNumber = i;
            executorService.execute(()->{
                try {
                    //获取令牌，成功则继续执行，否则阻塞；
                    semaphore.acquire();
                    test(threadNumber);
                    //释放令牌
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            });
        }

        System.out.println("结束了");
        executorService.shutdown();

    }

    public static void test(int threadNumber) throws Exception {
        Thread.sleep(10);
        log.info("{}", threadNumber);
    }

}
